<?php
/**
 * @version		$Id: articles.php 17130 2010-05-17 05:52:36Z eddieajau $
 * @copyright	Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of article records.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_content
 */
class AjaxWhoisModelLinks extends JModelList
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
	protected function populateState()
	{
		// Initialise variables.
		$app = JFactory::getApplication();

		// Adjust the context to support modal layouts.
		if ($layout = JRequest::getVar('layout', 'default')) {
			$this->context .= '.'.$layout;
		}

		$search = $app->getUserStateFromRequest($this->context.'.filter.title', 'filter_title');
		$this->setState('filter.title', $search);

		$which = $app->getUserStateFromRequest($this->context.'.filter.which', 'filter_which');
		if ($which == '') $which = 1;
		$this->setState('filter.which', $which);
		
		// List state information.
		parent::populateState('a.title', 'asc');
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'Links', $prefix = 'AjaxWhoisTable', $config = array()) {
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param	string		$id	A prefix for the store id.
	 *
	 * @return	string		A store id.
	 * @since	1.6
	 */
	protected function getStoreId($id = '') {
		// Compile the store id.
		$id	.= ':'.$this->getState('filter.title');
		$id	.= ':'.$this->getState('filter.which');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 */
	protected function getListQuery() {
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.title, a.which, a.url, a.home, a.target, a.published')
		);
		$query->from('#__aw_reg AS a');

		// Filter by extension.
		if ($title = $this->getState('filter.title')) {
			$title = $db->Quote('%'.$db->getEscaped($title, true).'%');
			$query->where('a.title LIKE ' . $title);
		}

		// Filter by which.
		$which = $this->getState('filter.which');
		if ($which == '') {
			$query->where("a.which = '1'");
		} else {
			$query->where("a.which = ".$which);
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');
		if ($orderCol == '') {
			$orderCol = 'a.title';
		}
		$query->order($db->getEscaped($orderCol.' '.$orderDirn));

		//echo nl2br(str_replace('#__','jos_',$query));
		return $query;
	}
	/**
	* Method to remove a item
	*
	* @access public
	* @return boolean True on success
	*/
	function delete($cid = array()) {
		$result = false;
		
		if (count( $cid )) {
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__aw_reg'
			. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		return true;
	}

	/**
	* Method to (un)publish a item
	*
	* @access public
	* @return boolean True on success
	*/
	function publish($cid = array()) {
		$task = JRequest::getVar( 'task' );
		switch ($task) {
			case "publish":
				$field = "published";
				$publish = 1;
				break;
			case "unpublish":
				$field = "published";
				$publish = 0;
				break;
		}
				
		if (count( $cid )) {
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			
			$query = 'UPDATE #__aw_reg'
			. ' SET '.$field.' = '.(int) $publish
			. ' WHERE id IN ( '.$cids.' )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		
		return true;
	}
	/**
	 * Method to duplicate styles.
	 *
	 * @param	array	An array of primary key IDs.
	 *
	 * @return	boolean	True if successful.
	 * @throws	Exception
	 */
	public function duplicate(&$pks)
	{
		// Initialise variables.
		$db		= $this->getDbo();

		$table = $this->getTable();

		foreach ($pks as $pk) {
			if ($table->load($pk, true)) {
				// Reset the id to create a new record.
				$table->id = 0;

				// Reset the home (don't want dupes of that field).
				$table->home = 0;

				// Alter the title.
				$m = null;
				if (preg_match('#\((\d+)\)$#', $table->title, $m)) {
					$table->title = preg_replace('#\(\d+\)$#', '('.($m[1] + 1).')', $table->title);
				} else {
					$table->title .= ' (2)';
				}

				if (!$table->check() || !$table->store()) {
					throw new Exception($table->getError());
				}
			} else {
				throw new Exception($table->getError());
			}
		}


		return true;
	}
	/**
	 * Method to set a template style as home.
	 *
	 * @param	int		The primary key ID for the style.
	 *
	 * @return	boolean	True if successful.
	 * @throws	Exception
	 */
	public function setHome($id = 0)
	{
		$app = JFactory::getApplication();
		
		// Initialise variables.
		$db		= $this->getDbo();

		$which = $app->getUserStateFromRequest($this->context.'.filter.which', 'filter_which');
		// Reset the home fields for the client_id.
		$db->setQuery(
			'UPDATE #__aw_reg' .
			' SET home = 0' .
			' WHERE which = '.(int) $which
		);

		if (!$db->query()) {
			throw new Exception($db->getErrorMsg());
		}

		// Set the new home style.
		$db->setQuery(
			'UPDATE #__aw_reg' .
			' SET home = 1' .
			' WHERE id = '.(int) $id
		);

		if (!$db->query()) {
			throw new Exception($db->getErrorMsg());
		}

		return true;
	}

}